﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class MainForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BindData();    
        }


        protected void BindData()
        {
            DataClassesDataContext ctx = new DataClassesDataContext();
            dataView.DataSource = from c in ctx.Categories
                                  select c;
            dataView.DataBind();

        }
        
        protected void RowEditing(object sender, GridViewEditEventArgs  e)
        {
            dataView.EditIndex = e.NewEditIndex;
            dataView.DataBind();
        }
        
        protected void RowUpdating(object sender, GridViewUpdateEventArgs   e)
        {
             
            Response.Write(e.RowIndex);
            Response.Write(e.NewValues[0] + " " + e.NewValues[1]);

            String id = dataView.Rows[e.RowIndex].Cells[2].Text ;
            TableCell cell = dataView.Rows[e.RowIndex].Cells[2];
           

            DataClassesDataContext ctx = new DataClassesDataContext();
            Category cat = (from c in ctx.Categories
                            where c.CategoryID == int.Parse(id)
                            select c).SingleOrDefault();

            cat.CategoryName =((TextBox) dataView.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
            cat.Description = ((TextBox) dataView.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
            ctx.SubmitChanges();
            dataView.EditIndex = -1;

            //Bind data to the GridView control.
            BindData();
        }

        protected void dataView_RowDeleting(Object sender, GridViewDeleteEventArgs e)
        {
            TableCell cell = dataView.Rows[e.RowIndex].Cells[2];
            Response.Write(dataView.Rows[e.RowIndex].Cells[2].Text);
            DataClassesDataContext ctx = new DataClassesDataContext();
            Category cat = (from c in ctx.Categories
                              where c.CategoryID==int.Parse(cell.Text)
                               select c).SingleOrDefault();

            ctx.Categories.DeleteOnSubmit(cat);
            ctx.SubmitChanges();
            BindData();
        }  





    }
}